<?php

namespace MoChat\App\WorkContact\Action\Dashboard;

use Hyperf\DbConnection\Db;
use MoChat\App\Common\Exception\CommonException;
use MoChat\Framework\Action\AbstractAction;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * @Controller
 */
class CorrelationClient extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     * })
     * @RequestMapping(path="/dashboard/workContact/correlationClient", methods="POST")
     */
    public function handle()
    {
        $params = $this->request->all();
        $this->validated($params);
        Db::beginTransaction();
        try {
//            $info = Db::table('client_contact_pivot')->lockForUpdate()
//                ->where('contact_id', $params['contactId'])
//                ->first();

//            if (!empty($info)) {
//                Db::table('client_contact_pivot')->delete($info->id);
//            }
            Db::table('client_contact_pivot')->insert([
                'client_id' => $params['clientId'],
                'contact_id' => $params['contactId'],
                'created_at' => date('Y-m-d H:i:s')
            ]);
            Db::commit();
        } catch (\Throwable $throwable) {
            Db::rollBack();
        }
        return [];
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'contactId' => 'required|integer',
            'clientId' => 'required|integer',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'contactId.required' => 'contactId必填',
            'contactId.integer' => 'contactId参数错误',
            'clientId.required' => 'clientId必填',
            'clientId.integer' => 'clientId参数错误',
        ];
    }

}
